package com.ruoyi.mobile.api;

import com.ruoyi.common.core.domain.AjaxResults;
import com.ruoyi.framework.app.service.IKUsersFraneworkService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * 微信授权登录
 *
 * @author gk
 * @date 2023-06-19
 */
@Api(tags = "微信授权登录")
@RestController
@Slf4j
@RequestMapping("/app")
public class WxLoginController {

    @Autowired
    private IKUsersFraneworkService ikUsersFraneworkService;


    // 配置对应的APPID
    private static String WX_APPID="wxe4eb4267e98b952a";
    // 配置对应的WX_APPSECRET
    private static String WX_APPSECRET="9d7dbf01572eef6a82f60a078c7cd69e";

    /**
     * Tea微信登录接口
     * @throws IOException
     */
    @ApiOperation(value = "Tea微信登录接口")
    @RequestMapping("wxLogin")
    public void wxLogin(HttpServletResponse response) throws IOException {
        // 因为是这测试域名这里暂时写死，
        String ym = "https://wechat.horgoscloud.cn/app";
        //这里是回调的url
        String redirect_uri = URLEncoder.encode(ym+"/callBack", "UTF-8");
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
                "appid=APPID" +
                "&redirect_uri=REDIRECT_URI"+
                "&response_type=code" +
                "&scope=SCOPE" +
                "&state=123#wechat_redirect";
        response.sendRedirect(url.replace("APPID",WX_APPID).replace("REDIRECT_URI",redirect_uri).replace("SCOPE","snsapi_userinfo"));
    }
//    /**
//     * Tea微信授权成功的回调函数
//     *
//     * @param request
//     * @param response
//     * @throws IOException
//     */
//    @ApiOperation(value = "Tea微信授权成功的回调函数")
//    @RequestMapping("/callBack")
//    protected void deGet(HttpServletRequest request, HttpServletResponse response)throws Exception {
//        //获取回调地址中返回的code
//        String code = request.getParameter("code");
//        //拼接url
//        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + WX_APPID + "&secret="
//                + WX_APPSECRET + "&code=" + code + "&grant_type=authorization_code";
//        // 根据code 去查微信用户的信息，返回的用户基本信息全部在JSONObject里面
//        JSONObject jsonObject = this.doGetJson(url);
//        //1.获取微信用户的openid
//        String openid = jsonObject.getString("openid");
//        System.out.println("获取微信用户的openid:"+openid);
//        //2.获取获取access_token
//        String access_token = jsonObject.getString("access_token");
//        System.out.println("获取微信用户的access_token:"+access_token);
//        String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openid
//                + "&lang=zh_CN";
//        //3.获取微信用户信息
//        JSONObject userInfo = this.doGetJson(infoUrl);
//        log.info(String.valueOf(userInfo));
//        System.out.println(userInfo);
////        //处理项目逻辑
////        ikUsersFraneworkService.callBack(userInfo,openid);
//    }

        /**
     * Tea微信授权成功的回调函数
     *
     * @param request
     * @param response
     * @throws IOException
     */
    @ApiOperation(value = "Tea微信授权成功的回调函数")
    @RequestMapping("/callBack")
    protected void deGet(HttpServletRequest request, HttpServletResponse response)throws Exception {
        //获取回调地址中返回的code
        String code = request.getParameter("code");
        //拼接url
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + WX_APPID + "&secret="
                + WX_APPSECRET + "&code=" + code + "&grant_type=authorization_code";
        // 根据code 去查微信用户的信息，返回的用户基本信息全部在JSONObject里面
        JSONObject jsonObject = this.doGetJson(url);
        //1.获取微信用户的openid
        String openid = jsonObject.getString("openid");
        System.out.println("获取微信用户的openid:"+openid);
        //2.获取获取access_token
        String access_token = jsonObject.getString("access_token");
        System.out.println("获取微信用户的access_token:"+access_token);
        String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openid
                + "&lang=zh_CN";
        //3.获取微信用户信息
        JSONObject userInfo = this.doGetJson(infoUrl);
        log.info(String.valueOf(userInfo));
        System.out.println(userInfo);
//        //处理项目逻辑
//        ikUsersFraneworkService.callBack(userInfo,openid);

        //保存openid和access_token到session
        request.getSession().setAttribute("openid", openid);
        request.getSession().setAttribute("access_token", access_token);
        request.getSession().setAttribute("token", ikUsersFraneworkService.callBack(userInfo,openid));
        response.sendRedirect("/");
    }


    @ApiOperation(value = "根据code获取token")
    @GetMapping("/getToken")
    protected AjaxResults getToken(String code)throws Exception {

        Assert.notNull(code, "获取用户code失败！");
        //拼接url
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + WX_APPID + "&secret="
                + WX_APPSECRET + "&code=" + code + "&grant_type=authorization_code";
        // 根据code 去查微信用户的信息，返回的用户基本信息全部在JSONObject里面
        JSONObject jsonObject = this.doGetJson(url);
        //1.获取微信用户的openid
        String openid = jsonObject.getString("openid");
        System.out.println("获取微信用户的openid:"+openid);
        //2.获取获取access_token
        String access_token = jsonObject.getString("access_token");
        System.out.println("获取微信用户的access_token:"+access_token);
        String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openid
                + "&lang=zh_CN";
        //3.获取微信用户信息
        JSONObject userInfo = this.doGetJson(infoUrl);
        log.info(String.valueOf(userInfo));
        System.out.println(userInfo);
        return  AjaxResults.success(ikUsersFraneworkService.callBack(userInfo,openid));
    }



    /**
     * 发送HttpClient请求，并且将请求的结果以JSONObject格式返回
     * @param url
     * @return
     * @throws IOException
     */
    public JSONObject doGetJson(String url) throws IOException {
        JSONObject jsonObject = null;
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        HttpResponse response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            String result = EntityUtils.toString(entity, "UTF-8");
            jsonObject = JSONObject.fromObject(result);
        }
        httpGet.releaseConnection();
        return jsonObject;
    }
}